/*
 * Udp.c
 *
 *  Created on: Oct 29, 2018
 *      Author: ax
 */
#include <Process.h>
#include <Socket/Ipnet/Udp.h>

#include <Sos.h>

#define LOCAL   10,0,0,1
#define PEER    10,0,0,210

#define SUM_PRD 8

#ifndef _XXX_
static Timestamp nsum = 0;
static uint64_t period = 0;
static uint32_t pkts = 0;
static uint32_t szall = 0;
static uint32_t pktsAll = 0;
#endif


RC
 Udp_echo(
    void
){
    Udp_Msg msg;

    if (NULL == (msg = Udp_receive()))
        return Process_EMPTY_LOOP;

    Udp_Msg ec = Udp_alloc();
    ec->DstPort = msg->SrcPort;
    ec->SrcPort = msg->DstPort;
    short sz = ec->Length = msg->Length;
    memcpy(&ec->Payload, &msg->Payload, sz);
    Udp_send(ec);

    Udp_free(msg);


    //summary for packet, TODO move this to System_Monitor.
    pkts++;
    szall += (uint64_t) sz;

    Timestamp cur = Timer_getStamp();
    if (nsum < cur) {
        nsum = cur + period;

        pktsAll += pkts;
        Log_dbg("[Net]: Bps-%d pps-%d, p-%d\n", szall / SUM_PRD, pkts / SUM_PRD, pktsAll);

        pkts = 0;
        szall = 0;
    }

    return Udp_SOK;
}


void
udpd(
    void
){
    if (Udp_SOK == Udp_open(Ip_makeIp4(LOCAL), Ip_makeIp4(PEER))) {
        Process_redirect(Process_SELF, (Process) Udp_echo, 0, NULL);
        #ifndef _XXX_
        period = (Uint64) 1000000000 * (Uint64) 10;
        nsum = Timer_getStamp() + period;
        #endif
    }
}
